package com.june.junemplayer.service;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS;
import static android.view.WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
import static android.view.WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH;

import static com.june.junemplayer.base.BaseApplication.getApplication;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.view.MotionEventCompat;
import androidx.lifecycle.ViewModelStoreOwner;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.june.junemplayer.R;
import com.june.junemplayer.controller.GlobalViewModelController;
import com.june.junemplayer.pojo.Song;
import com.june.junemplayer.service.MediaPlayerService;
import com.june.junemplayer.view.LocalSongListActivity;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

public class PlayingListView extends RelativeLayout implements View.OnClickListener{

    private MediaPlayerService mMediaPlayerService;

    private GlobalViewModelController mGlobalViewModelController;

    private WindowManager mWindowManager;
    private WindowManager.LayoutParams mLayoutParams;

    public boolean mIsShown;

    private Context mContext;
    private View mView;

    private TextView mPlayingListStyleTitle;
    private RecyclerView mPlayingList;
    private PlayingListAdapter mPlayingListAdapter;

    public PlayingListView(Context context) {
        this(context, null);
    }

    public PlayingListView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public PlayingListView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;

        mGlobalViewModelController = new GlobalViewModelController((ViewModelStoreOwner) getApplication());

        mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        //设置好悬浮窗的参数
        mLayoutParams = new WindowManager.LayoutParams();
        mLayoutParams.width = MATCH_PARENT;
        mLayoutParams.height = 1000;
        mLayoutParams.format = PixelFormat.RGBA_8888;
        mLayoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        mLayoutParams.flags = FLAG_NOT_TOUCH_MODAL | FLAG_WATCH_OUTSIDE_TOUCH | FLAG_LAYOUT_NO_LIMITS;

        //悬浮窗的开始位置，因为设置的是从左上角开始，所以屏幕左上角是x=0;y=0
        mLayoutParams.gravity = Gravity.START | Gravity.TOP;
        mLayoutParams.x = 0;
        mLayoutParams.y = 500;

        mView = LayoutInflater.from(context).inflate(R.layout.view_playing_list, this, true);
        mPlayingListStyleTitle=mView.findViewById(R.id.tv_PlayingListStyle);
        mPlayingList=mView.findViewById(R.id.rv_PlayingList);

        mPlayingListAdapter=new PlayingListAdapter(mGlobalViewModelController.getPlayingList());

        mIsShown=false;
        Intent intent = new Intent(mContext, MediaPlayerService.class);
        intent.putExtra("Mission", MediaPlayerService.PREPARE_PLAYER);
        mContext.bindService(intent, connectionMediaPlayerServiceConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    public void onClick(View v) {
        Log.d("JuneProcedureLog", getTag() + "----onClick");

        Log.d("June", String.valueOf(v.getId()));

        switch (v.getId()) {
        }
    }

    public String getTag() {
        return "PlayingListView";
    }

    private ServiceConnection connectionMediaPlayerServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            mMediaPlayerService = ((MediaPlayerService.MediaPlayerServiceBinder) iBinder).getService();
            Log.d("JuneProcedureLog", getTag() + "----onServiceConnect----PlayingListView");
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Log.d("JuneProcedureLog", getTag() + "----onServiceDisconnected----PlayingListView");

        }
    };

    public void show() {
        if(!mIsShown){
            mWindowManager.addView(mView, mLayoutParams);
        }
    }

    public void hide() {
        mWindowManager.removeView(mView);
    }

    public interface OnItemChildClickListener {
        void onItemChildClick(PlayingListAdapter adapter, View view, int position);
    }

    private class PlayingListAdapter extends RecyclerView.Adapter<PlayingListAdapter.PlayingListViewHolder> {
        private PlayingListAdapter mAdapter;
        private ArrayList<Song> mSongs;
        private final ItemTouchHelper mItemTouchHelper;
        private RecyclerView mParentRecyclerView = null;
        private OnItemChildClickListener mOnItemChildClickListener;

        private Song mPlayingSong;

        public PlayingListAdapter(ArrayList<Song> songs) {
            mAdapter = this;
            mSongs = songs;

            mPlayingSong=mGlobalViewModelController.getPlayingSong();

            final float dragElevation = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8,
                    mContext.getResources().getDisplayMetrics());

            mItemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(
                    ItemTouchHelper.UP | ItemTouchHelper.DOWN, 0 /* no swipe */) {

                @Override
                public boolean onMove(@NonNull RecyclerView view, RecyclerView.ViewHolder fromViewHolder,
                                      RecyclerView.ViewHolder toViewHolder) {
                    onItemMove(fromViewHolder.getAdapterPosition(), toViewHolder.getAdapterPosition());
                    return true;
                }

                @Override
                public void onSwiped(RecyclerView.ViewHolder viewHolder, int position) {
                }

                private static final int SELECTION_GAINED = 1;
                private static final int SELECTION_LOST = 0;
                private static final int SELECTION_UNCHANGED = -1;
                private int mSelectionStatus = SELECTION_UNCHANGED;

                @Override
                public void onChildDraw(@NonNull Canvas c, @NonNull RecyclerView recyclerView,
                                        @NonNull RecyclerView.ViewHolder viewHolder, float dX, float dY,
                                        int actionState, boolean isCurrentlyActive) {
                    super.onChildDraw(c, recyclerView, viewHolder, dX, dY,
                            actionState, isCurrentlyActive);
                    if (mSelectionStatus != SELECTION_UNCHANGED) {
                        viewHolder.itemView.setElevation(
                                mSelectionStatus == SELECTION_GAINED ? dragElevation : 0);
                        mSelectionStatus = SELECTION_UNCHANGED;
                    }
                }

                @Override
                public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
                    super.onSelectedChanged(viewHolder, actionState);
                    if (actionState == ItemTouchHelper.ACTION_STATE_DRAG) {
                        mSelectionStatus = SELECTION_GAINED;
                    } else if (actionState == ItemTouchHelper.ACTION_STATE_IDLE) {
                        mSelectionStatus = SELECTION_LOST;
                    }
                }
            });
        }

        @NonNull
        @Override
        public PlayingListViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.item_song, parent, false);
            return new PlayingListViewHolder(view);
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(@NonNull PlayingListViewHolder holder, int position) {
            holder.mSongInfo.setText(mSongs.get(position).getTitle()+" - "+mSongs.get(position).getArtist());

            holder.mRemoveImage.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    //删除
                }
            });

            if (mSongs.get(position)==mPlayingSong) {
                holder.mSongInfo.setTextColor(mContext.getColor(R.color.gold_color));
            } else {
                holder.mSongInfo.setTextColor(mContext.getColor(R.color.white));
            }

            if (mOnItemChildClickListener != null) {
                holder.mView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        getOnItemChildClickListener().onItemChildClick(PlayingListAdapter.this, v, holder.getAdapterPosition());
                    }
                });
            }
        }


        public OnItemChildClickListener getOnItemChildClickListener() {
            return mOnItemChildClickListener;
        }

        public void setOnItemChildClickListener(OnItemChildClickListener listener) {
            mOnItemChildClickListener = listener;
        }

        @Override
        public int getItemCount() {
            return mSongs == null ? 0 : mSongs.size();
        }

        public class PlayingListViewHolder extends RecyclerView.ViewHolder implements View.OnTouchListener{
            private final View mView;

            private final TextView mSongInfo;
            private final ImageView mDraggableImage;
            private final ImageView mRemoveImage;

            public PlayingListViewHolder(View view) {
                super(view);
                mView = view;
                mSongInfo = view.findViewById(R.id.tv_SongInfo);
                mDraggableImage = view.findViewById(R.id.img_Draggable);
                mRemoveImage = view.findViewById(R.id.img_Remove);

                mDraggableImage.setOnTouchListener(this);
            }
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (MotionEventCompat.getActionMasked(event)) {
                    case MotionEvent.ACTION_DOWN:
                        mItemTouchHelper.startDrag(this);
                }
                return false;
            }
        }

        public void onItemMove(int fromPosition, int toPosition) {
            Log.d("June", "onItemMove fromPosition:" + fromPosition + " toPosition:" + toPosition);
            if (fromPosition >= 0 && toPosition >= 0) {
                //改变数据位置
                Song song=mGlobalViewModelController.removeFromPlayingList(fromPosition);
                mGlobalViewModelController.addToPlayingList(toPosition,song);
            } else {
                // There may be - 1
                Log.e("June", "position in onItemMove < 0 "+fromPosition+" -> "+toPosition);
            }
            notifyItemChanged(fromPosition);
            notifyItemChanged(toPosition);
            notifyItemMoved(fromPosition, toPosition);
        }
    }
}
